package com.qf.service;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsCategoryMapper;
import com.qf.pojo.DtsCategory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
   @Autowired
    private DtsCategoryMapper categoryMapper;

    @Override
    public IPage<DtsCategory> queryCategoryPage(Integer id, String name, Integer page, Integer limit, String sort, String order) {
        //1. 创建分页对象
        //参数1: 当前页, 参数2: 每页显示条数
        IPage<DtsCategory> ipage = new Page<>(page, limit);

        //2. 封装查询对象
        QueryWrapper<DtsCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", false);

        //判断查询条件不为空拼接查询条件

        if (id!=null) {
            queryWrapper.eq("id", id);
        }
        if (!StringUtils.isEmpty(name)) {
            queryWrapper.like("name", name);
        }


        //排序
        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            //判断排序方式是否为升序
            if (order.equalsIgnoreCase("asc")) {
                queryWrapper.orderByAsc(sort);
            } else {
                //降序
                queryWrapper.orderByDesc(sort);
            }
        }


        //3. 查询并返回结果
        IPage<DtsCategory> resultPage = categoryMapper.selectPage(ipage, queryWrapper);


        return resultPage;
    }

    @Override
    public List<DtsCategory> findByLabel() {
//        QueryWrapper<DtsCategory> queryWrapper = new QueryWrapper<>();
        List<DtsCategory> list = categoryMapper.findByLabel();
        return list;
    }

    @Override
    public List<DtsCategory> findByPid(Integer pid) {
        List<DtsCategory> categoryList = categoryMapper.findByPid(pid);
        return categoryList;
    }

    @Override
    public int add(DtsCategory category) {
        category.setDeleted(false);
        //创建时间
        category.setAddTime(new Date());
        //修改时间
        category.setUpdateTime(new Date());
        int insert = categoryMapper.insert(category);
        return insert;
    }

    @Override
    public int update(DtsCategory category) {
        category.setUpdateTime(new Date());
        int insert = categoryMapper.insert(category);
        return insert;
    }

    @Override
    public void deleteByid(Integer id) {
        QueryWrapper<DtsCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        categoryMapper.delete(queryWrapper);


    }

}
